<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">档案资料上传</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">曾经获得各类证书。</span>
      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column;padding-bottom: 5vh;margin-top: 3vh;margin-bottom: 3vh ">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9;height: 7vh;">
          <span style="font-weight: bold;font-size: 1.1rem;line-height: 7vh;margin-left: 1.5vw">填写信息</span>
        </div>
        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="档案标题" prop="title" required>
              <el-input placeholder="请填写档案标题" v-model="ruleForm.title" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="证书类型" prop="certificateType" required>
              <el-radio-group v-model="ruleForm.certificateType">
                <el-radio label="其它证书">其它证书</el-radio>
                <el-radio label="学位证书">学位证书</el-radio>
                <el-radio label="学历证书">学历证书</el-radio>
                <el-radio label="语言证书">语言证书</el-radio>
                <el-radio label="居民身份证">居民身份证</el-radio>
                <el-radio label="教师资格证">教师资格证</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="获得时间" prop="obtainTime" required>
              <el-date-picker
                  v-model="ruleForm.obtainTime"
                  type="date"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="证书编号" prop="certificateNumber" required>
              <el-input placeholder="请输入证书编号" v-model="ruleForm.certificateNumber" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="授予机构" prop="issuingInstitution" required>
              <el-input placeholder="请输入授予机构或院校名称" v-model="ruleForm.issuingInstitution" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="是否同步" prop="syncStatus">
              <el-select v-model="ruleForm.syncStatus" style="width: 34vw;" placeholder="请选择是否同步">
                <el-option label="是" :value="'是'"></el-option>
                <el-option label="否" :value="'否'"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联课题" prop="projectId">
              <el-select v-model="ruleForm.projectId" placeholder="请选择本成果所属课题,以便使用结题助手功能" style="width: 34vw;">
                <el-option
                    v-for="project in longitudinalProjects"
                    :key="project.id"
                    :label="project.projectName"
                    :value="project.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注信息" prop="remarks">
              <el-input
                  type="textarea"
                  :rows="4"
                  placeholder="请输入备注信息"
                  v-model="ruleForm.remarks"
                  style="width: 34vw;">
              </el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex;justify-content: center;margin-top: 2vh">
            <button @click="submit" class="upload-button" style="width: 10vw;" :disabled="isSubmitting">
              {{ isSubmitting ? '上传中...' : '上 传' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import request from "@/utils/request.js"
import { useRouter } from 'vue-router'
import PdfPreview from "@/components/PdfPreview.vue"
import {saveCertification} from "@/api/Manage/Certification.js";
import {getCompletedLongitudinal} from "@/api/Research/Longitudinal.js";
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const router = useRouter()
const ruleFormRef = ref(null)
const pdfPreviewRef = ref(null)
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

const ruleForm = reactive({
  title: '',
  certificateType: '',
  obtainTime: '',
  certificateNumber: '',
  issuingInstitution: '',
  projectId: '',
  remarks: '',
  pdfPath: '',
  pdfUrl: '',
  syncStatus:"是",
})

const longitudinalProjects = ref([]) // Store the projects

const rules = reactive({
  title: [
    { required: true, message: '请输入档案标题', trigger: 'blur' }
  ],
  certificateType: [
    { required: true, message: '请选择证书类型', trigger: 'change' }
  ],
  obtainTime: [
    { required: true, message: '请选择获得时间', trigger: 'change' }
  ],
  certificateNumber: [
    { required: true, message: '请输入证书编号', trigger: 'blur' }
  ],
  issuingInstitution: [
    { required: true, message: '请输入授予机构', trigger: 'blur' }
  ]
})

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

const formatDate = (date) => {
  if (!date) return ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const submit = async () => {
  try {
    isSubmitting.value = true
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        // 如果有旋转，先保存旋转
        if (hasRotations.value && currentRotations.value.length > 0 && ruleForm.pdfPath) {
          try {
            // 组装批量更新请求数据
            const batchData = {
              filePath: ruleForm.pdfPath, // PDF文件路径
              pages: currentRotations.value.map(rotation => ({
                pageNumber: rotation.pageIndex + 1, // 页码从1开始
                rotation: rotation.rotation // 旋转角度
              }))
            }

            console.log('批量更新旋转请求数据:', batchData)

            const rotationResult = await batchUpdatePdfPages(batchData)
            console.log('批量更新旋转结果:', rotationResult)

            if (rotationResult.code !== "0") {
              ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
              return
            }



            // 重置旋转状态
            hasRotations.value = false
            currentRotations.value = []

            // 通知PDF预览组件重新加载
            if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
              await pdfPreviewRef.value.reloadPDF(ruleForm.pdfPath)
            }

          } catch (rotationError) {
            console.error('保存旋转失败:', rotationError)
            ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
            return
          }
        }

        const formData = {
          ...ruleForm,
          obtainTime: formatDate(ruleForm.obtainTime)
        }
        try {
          const res=await saveCertification(formData);
          if (res.code===1)
          {
            ElMessage.success('上传成功')
            router.push("/main/result/Certification")
          }
          else
          {
            ElMessage.error('上传失败')
          }

        }
        catch (error)
        {
          ElMessage.error('请求失败，请重试')
        }
      } else {
        ElMessage.error('请填写必填项')
        return false
      }
    })
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

const updatePdfPath = (newPath) => {
  ruleForm.pdfPath = newPath.firstImageUrl
}

onMounted(async () => {
  try {
    const response = await getCompletedLongitudinal();
    if (response.code === 1 && Array.isArray(response.data)) {
      longitudinalProjects.value = response.data;
    } else {
      ElMessage.error('获取结题的纵向课题失败');
    }
  } catch (error) {
    console.error('获取结题的纵向课题出错:', error);
    ElMessage.error('获取结题的纵向课题失败，请刷新页面重试');
  }
});
</script>

<style scoped>
.upload-button {
  color: white;
  height: 3.8vh;
  width: 6.5vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
}

.upload-button:hover:not(:disabled) {
  background-color: #009b77;
}

.upload-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

canvas {
  display: block;
  margin: 0 auto;
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}
</style>
